package com.syl.springcloud.authorization.service;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.*;

import static com.syl.springcloud.authorization.constant.BaseConstant.*;

/**
 * 自定义权限路由资源
 * @author syl
 * @create 2018-08-08 15:16
 **/
@Component
public class CustomAuthorityRouteSource implements FilterInvocationSecurityMetadataSource {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final Map<String,String> URL_ROLE_MAP = new HashMap<String,String>(){{
        // 匹配url必须以/结尾 除非为**
        put("/home/**", "ROLE_ADMIN"+SPLIT_SYMBOL +"ROLE_USER");
        put("/token/**", "ROLE_ADMIN"+SPLIT_SYMBOL +"ROLE_USER");
        put("/oauth/**", "ROLE_ADMIN"+SPLIT_SYMBOL +"ROLE_USER");
        put("/welcome/**","ROLE_ADMIN");
        put("/user/**","ROLE_ADMIN,ROLE_USER");
    }};

    private final List<String> ANONYMOUS_URL_LIST = new ArrayList<String>(){{
        add("/");
        add("/login/**");
        add("/login?logout");
        add("/logout/");//退出登录成功提示
        add("/error/**");
        add("/aes/**");
    }};

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        for(Map.Entry<String,String> entry: URL_ROLE_MAP.entrySet()){
            if(antPathMatcher.match(entry.getKey(),url)){
                return SecurityConfig.createList(entry.getValue().split(SPLIT_SYMBOL));
            }
        }
        //匹配匿名列表
        for (String anUrl : ANONYMOUS_URL_LIST) {
            if(antPathMatcher.match(anUrl,url)){
                return SecurityConfig.createList(ANONYMOUS_ROLE);
            }
        }
        //还是没有匹配到,默认最基本用户
        return SecurityConfig.createList(LOWLINESS_ROLE);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
